<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="/webjars/layui/2.5.6/css/layui.css">
    <script src="/webjars/layui/2.5.6/layui.js" type="text/javascript"></script>
    <base href="/user/">
</head>
<body>

<script id="userTool" type="text/html">
    <button class="layui-btn" onclick="userAdd()">添加</button>
    <button class="layui-btn" onclick="batchDel()">批量删除</button>
</script>
<script id="userDCL" type="text/html">
    <button class="layui-btn" lay-event="userUpdate">修改</button>
</script>

<div>


    <table id="userTable" lay-filter="userTable" class="layui-table"></table>
</div>

<div id="userHandler" style="display: none">
    <form class="layui-form" id="userForm" lay-filter="userForm" style="padding: 35px;">
        <div class="layui-form-item">
            <label class="layui-form-label">用户编号</label>
            <div class="layui-input-inline">
                <input type="text" name="id" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
                <input type="text" name="username" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户密码</label>
            <div class="layui-input-inline">
                <input type="text" name="password" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-inline">
                <input type="text" name="email" required lay-verify="email" placeholder="请输入正确的邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">头像</label>
            <div class="layui-input-inline">
                <img id="imghead"  class="logo-size" src="/images/jiahao.png" onclick="xuanze()"  style="width: 50px;cursor: pointer;border-radius: 50%"/>
                <input id="filgo" style="display: none" type="file" name="file" onchange="changeToop('filgo','imghead');" value="上传图片"> </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">可用|禁用</label>
            <div class="layui-input-block">
                <input name="locked" type="checkbox" checked value="1" lay-skin="switch">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-inline">
                <select name="roleId" id="roleId"  lay-verify="required">
                </select>
            </div>
        </div>
    </form>
</div>
<script type="text/html" id="titleTpl">
    {{#  if(d.locked==1){ }}
    <div class="layui-form-item">
        <label class="layui-form-label">可用|禁用</label>
        <div class="layui-input-block" userId="{{d.id}}">
            <input type="checkbox" lay-filter="switchTest" checked  value="1" lay-skin="switch">
        </div>
    </div>
    {{#  } else { }}
    <div class="layui-form-item">
        <label class="layui-form-label">可用|禁用</label>
        <div class="layui-input-block" userId="{{d.id}}">
            <input type="checkbox" lay-filter="switchTest" value="1" lay-skin="switch">
        </div>
    </div>
    {{#  } }}
</script>
</body>
<script>
    function xuanze() {
        Id('filgo').click();
    }
    //定义id选择器
    function Id(id){
        return document.getElementById(id);
    }
    //入口函数，两个参数分别为<input type='file'/>的id，还有一个就是图片的id，然后会自动根据文件id得到图片，然后把图片放到指定id的图片标签中
    function changeToop(fileid,imgid){
        var file = Id(fileid);
        if(file.value==''){
            //设置默认图片
            Id("imghead").src='/images/jiahao.png';
        }else{
            preImg(fileid,imgid);
        }
    }
    //获取input[file]图片的url Important
    function getFileUrl(fileId) {
        var url;
        var file = Id(fileId);
        var agent = navigator.userAgent;
        if (agent.indexOf("MSIE")>=1) {
            url = file.value;
        } else if(agent.indexOf("Firefox")>0) {
            url = window.URL.createObjectURL(file.files.item(0));
        } else if(agent.indexOf("Chrome")>0) {
            url = window.URL.createObjectURL(file.files.item(0));
        }
        return url;
    }
    //读取图片后预览
    function preImg(fileId,imgId) {
        var imgPre =Id(imgId);
        imgPre.src = getFileUrl(fileId);
    }

    function userAdd() {
        userDCL("add");
    }
    function userUpdate(data) {
        userDCL("update",data);
    }

    function userDCL(path,data) {
        layui.use(['table', 'form', 'jquery', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;
            var layer = layui.layer;
            var msg="修改"
            $("#filgo").val('');
            if(path=="add"){
                $("#userForm")[0].reset();
                $("#imghead")[0].src='/images/jiahao.png';
                msg="添加";
            }else {
                data.roleId=data.role.roleId;
                form.val("userForm",data);
                console.log(data);
                $("#imghead")[0].src="/images/"+data.img;

            }
            layer.open({
                type: 1,
                title: msg,
                area: ["500px","450px"],
                content: $("#userHandler"),
                btn: ['确定', '取消'],
                yes() {
                    // var formzz = $(this).parent().prev().prev().find('input').closest("form");

                    let user = form.val("userForm");
                    var formData = new FormData($("#userForm")[0]);
                    console.log(user)
                    console.log(formData)
                    $.ajax({
                        type: "post",
                        url: path,
                        data: formData,
                        contentType: false,//告诉客户端不要设置Content-Type 请求头部
                        processData: false,//告诉客户端不处理过程数据
                        success: function (data) {//完成后的事件
                                layer.close(layer.index)
                                layer.msg(msg);
                                form.render('select');
                                table.reload("userTable")
                            // $(".update_img").attr("src", data.img_src);//data.img_src得到图片的地址
                        },
                        error: function (error) {//出现错误时的事件
                            layer.msg("上传图片失败");
                        }
                    });


                    // $.post(path,user).done(({msg})=>{
                    //     layer.close(layer.index)
                    //     layer.msg(msg);
                    //     form.render('select');
                    //     table.reload("userTable")
                    // })
                }
            })
        })
    }
    function searchByUserName(){
        var $=layui.jquery;
        var status=$("#status").val();
        layui.table.reload('userTable',{where:{status:status}})
    }
    layui.use(['table','form','laydate','jquery','element','layedit'],function () {
        //创建一个编辑器

        let table=layui.table;
        let form=layui.form;
        let $=layui.jquery;
        let laydate=layui.laydate;
        let layedit=layui.layedit;
        table.render({
            id:"userTable",
            elem:"#userTable",
            url:"list",
            toolbar:"#userTool",
            cols:[
                [
                    {type:"checkbox"},
                    {title:"用户编号",field:"id"},
                    {title:"用户名称",field:"username"},
                    {title:"用户密码",field:"password"},
                    {title:"用户邮箱",field:"email"},
                    {title:"用户状态",templet: '#titleTpl'},
                    {title:"角色",templet:`<div><span>{{d.role.roleName}}</span></div>`},
                    {title:"操作",toolbar: "#userDCL"}
                ]
            ],
            page:{
                limit:6,
                limits:[9,12,15]
            }
        });
        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            var status=this.checked ? '1' : '0';
            var id=$(this).parent().attr("userId");
            console.log(roleId+"编号:修改"+status)
            $.post("updateStatus",{id:id,locked:status}).done(({msg})=>{
                layer.msg(msg);
            })
        });
        table.on("tool(userTable)",function ({data,event}) {
            switch (event) {
                case "userUpdate":
                    userUpdate(data);
            }
        })
        $.get("/role/roleList",({data})=>{
            for (let d of data) {
                console.log(d)
                var option=$("<option></option>");
                option.html(d.roleName);
                option.val(d.roleId);
                $("#roleId").append(option);
            }
            form.render('select');
        })


    })
    //批量删除
    function batchDel() {
        layui.use(['table','layer','jquery'],function () {
            var table=layui.table;
            var layer=layui.layer;
            var $=layui.jquery;
            var product=table.checkStatus("userTable").data;
            var ids=product.map(product=>"ids="+product.id).join("&")
            if(ids==""){
                layer.msg("请选择要删除的产品")
                return;
            }
            console.log(product)
            console.log(ids)
            $.get("patchDel?"+ids,({msg})=>{
                layer.msg(msg)
                table.reload("userTable");
            })

        })
    }
</script>
</body>
</html>